package com.hrt.util;

import java.text.SimpleDateFormat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hrt.bean.Sequence;

@Service
@Transactional
public class CodeGenaratServiceImpl implements CodeGenarateService {

	@Autowired
	private CodeGenarateDao dao;

	/* (non-Javadoc)
	 * @see com.hrt.util.CodeGenarateService#genarate(java.lang.String)
	 */
	@Override
	public synchronized String genarate(String tableName) {
		StringBuffer nextCode = new StringBuffer();

		Sequence seq= dao.getNextSequence(tableName);
		Long nextId =seq.getMaxId();
		String nextIdStr = String.valueOf(nextId);
		int len = nextIdStr.length();
		String prefix = seq.getPrefix();
		nextCode.append(prefix+"_");
	
		Long num = seq.getNums();
		int prefix_len = num.intValue() - len;
		if (prefix_len > 0) {
			while (prefix_len > 0) {
				nextCode.append("0");
				prefix_len--;
			}
		}
		nextCode.append(nextId);
		System.out.println(nextCode.toString());
		
		return nextCode.toString();
	}

	
	/* (non-Javadoc)
	 * @see com.hrt.util.CodeGenarateService#saveSequence(com.hrt.bean.Sequence)
	 */
	@Override
	public void saveSequence(Sequence seq) {
		// TODO Auto-generated method stub
		try {
			dao.saveEntity(seq);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	/* (non-Javadoc)
	 * @see com.hrt.util.CodeGenarateService#deleteSequence(java.lang.Long)
	 */
	@Override
	public void deleteSequence(Long seqId) {
		// TODO Auto-generated method stub
		try {
			Sequence seq=dao.getById(seqId);
			
			dao.updateEntity(seq);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
